<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Match_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
	}

	function search(){
		$team	  = $this->input->get('team',TRUE);
		if($team){
			$teamArray = $this->db->where("name", $team)->get(TBL_SPORT_TEAM)->result();
			$teamIdArray = array(0);
			foreach($teamArray as $item){
				$teamIdArray[] = $item->id;
			}
			$teamIdStr = implode(',',$teamIdArray); 
			$total = count( $this->db->where("home IN($teamIdStr) OR away IN($teamIdStr)")->get(TBL_MATCH)->result() );
		}else{
			$total = count( $this->db->get(TBL_MATCH)->result() );
		}
		
		$records_per_page = 25;
		$per_page = intval ( $this->input->get('per_page',TRUE) );
		$per_page = ( $per_page > 0) ? $per_page : 0; 
		
		$pagination = create_pagination( 
								$uri = "admin/dataman/match/show?team=$team", 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
		if($team){
			$records = $this->db->where("home IN($teamIdStr) OR away IN($teamIdStr)")->order_by('start_time','desc')->limit($records_per_page, $per_page )->get(TBL_MATCH)->result();
		}else{					
			$records = $this->db->order_by('start_time','desc')->limit($records_per_page, $per_page )->get(TBL_MATCH)->result();
		}
		return array('pagination'=> $pagination, 'records'=>$records, 'total_records'=>$total );
	}
	
	function match_submit(){
		$TOURNAMENT = $this->tournament_entity->init('id', $_POST['tournament_id']);
		$dateTimeStart = sysDateTimeFormat($TOURNAMENT->getStartTime());
		$dateTimeEnd = sysDateTimeFormat($TOURNAMENT->getEndTime());
		
		if(!isset($_POST['id'])){
			$startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			$convertionRate = $_POST['convertion_rate'];
			$convertionEnable = !isset($_POST['convertion_enable']) ? 'no':'yes';
			
			$pcArr = explode(':',$convertionRate);
			$convertionRate =  trim( $pcArr[0] ) .":". trim( $pcArr[1] ) ;
			
			if( !isset($pcArr[0]) OR ! $this->phpvalidator->is_natural($pcArr[0]) OR $pcArr[0]< 0 ){
				echo "Convertion rate is not valid.";
				exit();
			}
			
			if( !isset($pcArr[1]) OR ! $this->phpvalidator->is_natural($pcArr[1]) OR $pcArr[1]< 0 ){
				echo "Convertion rate is not valid.";
				exit();
			}
			
			if($startTime == 0 OR $endTime== 0 ){
				echo "Datetime not validated.";exit();
			}
			if($startTime < $TOURNAMENT->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";exit();
			}
			if($endTime > $TOURNAMENT->getEndTime()){
				echo "End time not validated. (> {$dateTimeEnd})";exit();
			}
			if($endTime <= time()){
				echo "End time not validated. (Can not < current time)";exit();
			}
			if($_POST['away'] == $_POST['home']){
				echo "Home and Away can not duplicate.";exit();
			}
		/*	if($_POST['home_score']){
				if(! $this->phpvalidator->is_natural($_POST['home_score']) OR $_POST['home_score'] < 0){
					echo "Home score is not valid.";
					exit();
				}
			}
			if($_POST['home_wickets']){
				if(! $this->phpvalidator->is_natural($_POST['home_wickets']) OR $_POST['home_wickets'] < 0){
					echo "Home wickets is not valid.";
					exit();
				}
			}
			if($_POST['home_overs']){
				if(! $this->phpvalidator->is_numeric($_POST['home_overs']) OR $_POST['home_overs'] < 0){
					echo "Home overs is not valid.";
					exit();
				}
			}
		*/	
		/*	if(! $this->phpvalidator->is_natural($_POST['home_runs']) OR $_POST['home_runs'] < 0){
				echo "Home runs is not valid.";
				exit();
			}	*/
		/*	if($_POST['away_score']){
				if(! $this->phpvalidator->is_natural($_POST['away_score']) OR $_POST['away_score'] < 0){
					echo "Away score is not valid.";
					exit();
				}
			}
			if($_POST['away_wickets']){
				if(! $this->phpvalidator->is_natural($_POST['away_wickets']) OR $_POST['away_wickets'] < 0){
					echo "Away wickets is not valid.";
					exit();
				}
			}
			if($_POST['away_overs']){
				if(! $this->phpvalidator->is_numeric($_POST['away_overs']) OR $_POST['away_overs'] < 0){
					echo "Away overs is not valid.";
					exit();
				}
			}
		*/	
		/*	if(! $this->phpvalidator->is_natural($_POST['away_runs']) OR $_POST['away_runs'] < 0){
				echo "Away runs is not valid.";
				exit();
			}	*/
			
			$sport_id = intval($_POST['sport_id']);
			//if sport_id = 1: Test cricket: DRAWN | other: NOT DRAWN
			
			$newId = $this->match_entity->createNewMatchEntity();
			$MATCH = $this->match_entity->init('id', $newId);
			
			$MATCH->setHome($_POST['home']);
			$MATCH->setHomeScore(strlen($_POST['home_score']) ? $_POST['home_score'] : '');
			$MATCH->setHomeWickets(strlen($_POST['home_wickets']) ? $_POST['home_wickets']: '');
			$MATCH->setHomeOvers(strlen($_POST['home_overs']) ? $_POST['home_overs']: '');
		//	$MATCH->setHomeRuns($_POST['home_runs']);
			$MATCH->setAway($_POST['away']);
			$MATCH->setAwayScore(strlen($_POST['away_score']) ? $_POST['away_score']: '');
			$MATCH->setAwayWickets(strlen($_POST['away_wickets']) ? $_POST['away_wickets']: '');
			$MATCH->setAwayOvers(strlen($_POST['away_overs']) ? $_POST['away_overs']: '');
		//	$MATCH->setAwayRuns($_POST['away_runs']);
			$MATCH->setResult($_POST['result']);
			$MATCH->setStartTime($startTime);
			$MATCH->setEndTime($endTime);
			$MATCH->setBetEnable('yes');
			$MATCH->setTournamentId($_POST['tournament_id']);
			$MATCH->setConvertionRate($convertionRate);
			$MATCH->setEnableConvertion($convertionEnable);
			$MATCH->setEmailNotifyEnable($this->input->post('email_notify_enable',NULL));
			$MATCH->setSmsNotifyEnable($this->input->post('sms_notify_enable',NULL));
			
			$MATCH->setFeedType($this->input->post('feed_type',NULL));
			$MATCH->setFeedKey($this->input->post('feed_key',NULL));
			$MATCH->setFeedMatchId($this->input->post('feed_match_id',NULL));
			$MATCH->setFeedCategoryId($this->input->post('feed_category_id',NULL));
			$MATCH->setTitle($this->input->post('title',NULL));
			
			if($startTime > time()){
				$status = 'upcoming';
			}else{
				$status = 'living';
			}
			$MATCH->setStatus($status);
			$MATCH->setSportId($sport_id);
			
			$MATCH->update();
			
			$event_category_id = $this->event_category_entity->createNewEventCategoryEntity($MATCH->getId());
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $event_category_id);
			$EVENT_CATEGORY->setCategory("Who will win the match");
			$EVENT_CATEGORY->setMatchId($newId);
			$EVENT_CATEGORY->setStatus('living');
			$EVENT_CATEGORY->setIsRoot('yes');
			$EVENT_CATEGORY->update();
			
			$HOME_TEAM = clone_($this->team_entity->init('id',$_POST['home']));
			$AWAY_TEAM = $this->team_entity->init('id',$_POST['away']);
			
			$event_id = $this->event_entity->createNewEventEntity();
			$EVENT = $this->event_entity->init('id', $event_id);
			$EVENT->setName($HOME_TEAM->getName());
			$EVENT->setTeamId($HOME_TEAM->getId());
			$EVENT->setMatchId($newId);
			$EVENT->setStatus('living');
			$EVENT->setEventCategoryId($event_category_id);
			$EVENT->setStartTime($startTime);
			$EVENT->setEndTime($endTime);
			$EVENT->setBetEnable('yes');
			$EVENT->setOdds(1);
			$EVENT->setIsRoot('yes');
			$EVENT->update();
			
			if($sport_id == 1){
				$EVENT_CATEGORY->setCategory("Match Result");
				$EVENT_CATEGORY->update();
				
				$event_id = $this->event_entity->createNewEventEntity();
				$EVENT = $this->event_entity->init('id', $event_id);
				$EVENT->setName("Draw");
				$EVENT->setTeamId(0);
				$EVENT->setMatchId($newId);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				$EVENT->setStartTime($startTime);
				$EVENT->setEndTime($endTime);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds(1);
				$EVENT->setIsRoot('yes');
				$EVENT->update();
			}
			
			$event_id = $this->event_entity->createNewEventEntity();
			$EVENT = $this->event_entity->init('id', $event_id);
			$EVENT->setName($AWAY_TEAM->getName());
			$EVENT->setTeamId($AWAY_TEAM->getId());
			$EVENT->setMatchId($newId);
			$EVENT->setStatus('living');
			$EVENT->setEventCategoryId($event_category_id);
			$EVENT->setStartTime($startTime);
			$EVENT->setEndTime($endTime);
			$EVENT->setBetEnable('yes');
			$EVENT->setOdds(1);
			$EVENT->setIsRoot('yes');
			$EVENT->update();
			 
			 
			if($this->input->post('use_default_event',TRUE) == 'yes'){ $this->add_default_event_to_match(0,$MATCH->getId(),$sport_id );}
		
			$event_category_id = $this->event_category_entity->createNewEventCategoryEntity($MATCH->getId());
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $event_category_id);
			$EVENT_CATEGORY->setCategory("Who will win the Toss?");
			$EVENT_CATEGORY->setMatchId($newId);
			$EVENT_CATEGORY->setStatus('living');
			$EVENT_CATEGORY->setIsRoot(NULL);
			$EVENT_CATEGORY->update();
			 
			$event_id = $this->event_entity->createNewEventEntity();
			$EVENT = $this->event_entity->init('id', $event_id);
			$EVENT->setName($HOME_TEAM->getName());
			$EVENT->setTeamId($HOME_TEAM->getId());
			$EVENT->setMatchId($newId);
			$EVENT->setStatus('living');
			$EVENT->setEventCategoryId($event_category_id);
			$EVENT->setStartTime($startTime);
			$EVENT->setEndTime($endTime);
			$EVENT->setBetEnable('yes');
			$EVENT->setOdds(1);
			$EVENT->setIsRoot(NULL);
			$EVENT->update();
			
			$event_id = $this->event_entity->createNewEventEntity();
			$EVENT = $this->event_entity->init('id', $event_id);
			$EVENT->setName($AWAY_TEAM->getName());
			$EVENT->setTeamId($AWAY_TEAM->getId());
			$EVENT->setMatchId($newId);
			$EVENT->setStatus('living');
			$EVENT->setEventCategoryId($event_category_id);
			$EVENT->setStartTime($startTime);
			$EVENT->setEndTime($endTime);
			$EVENT->setBetEnable('yes');
			$EVENT->setOdds(1);
			$EVENT->setIsRoot(NULL);
			$EVENT->update();
			
			if($sport_id == 1){
				$event_category_id = $this->event_category_entity->createNewEventCategoryEntity($MATCH->getId());
				$EVENT_CATEGORY = $this->event_category_entity->init('id', $event_category_id);
				$EVENT_CATEGORY->setCategory("Who will take the 1st innings Lead?");
				$EVENT_CATEGORY->setMatchId($newId);
				$EVENT_CATEGORY->setStatus('living');
				$EVENT_CATEGORY->setIsRoot(NULL);
				$EVENT_CATEGORY->update();
				 
				$event_id = $this->event_entity->createNewEventEntity();
				$EVENT = $this->event_entity->init('id', $event_id);
				$EVENT->setName($HOME_TEAM->getName());
				$EVENT->setTeamId($HOME_TEAM->getId());
				$EVENT->setMatchId($newId);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				$EVENT->setStartTime($startTime);
				$EVENT->setEndTime($endTime);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds(1);
				$EVENT->setIsRoot(NULL);
				$EVENT->update();
				
				$event_id = $this->event_entity->createNewEventEntity();
				$EVENT = $this->event_entity->init('id', $event_id);
				$EVENT->setName($AWAY_TEAM->getName());
				$EVENT->setTeamId($AWAY_TEAM->getId());
				$EVENT->setMatchId($newId);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				$EVENT->setStartTime($startTime);
				$EVENT->setEndTime($endTime);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds(1);
				$EVENT->setIsRoot(NULL);
				$EVENT->update();
			}
		}else{
			$startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			
			$convertionRate = $_POST['convertion_rate'];
			$convertionEnable = !isset($_POST['convertion_enable']) ? 'no':'yes';
			
			$pcArr = explode(':',$convertionRate);
			$convertionRate =  trim( $pcArr[0] ) .":". trim( $pcArr[1] ) ;
			
			if( !isset($pcArr[0]) OR ! $this->phpvalidator->is_natural($pcArr[0]) OR $pcArr[0]< 0 ){
				echo "Convertion rate is not valid.";
				exit();
			}
			
			if( !isset($pcArr[1]) OR ! $this->phpvalidator->is_natural($pcArr[1]) OR $pcArr[1]< 0 ){
				echo "Convertion rate is not valid.";
				exit();
			}
			
			if($startTime == 0 OR $endTime== 0 ){
				echo "Datetime not validated.";exit();
			}
			if($startTime < $TOURNAMENT->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";exit();
			}
			if($endTime > $TOURNAMENT->getEndTime()){
				echo "End time not validated. (> {$dateTimeEnd})";exit();
			}
			
		/*	if($_POST['home_score']){
				if(! $this->phpvalidator->is_natural($_POST['home_score']) OR $_POST['home_score'] < 0){
					echo "Home score is not valid.";
					exit();
				}
			}
			if($_POST['home_wickets']){
				if(! $this->phpvalidator->is_natural($_POST['home_wickets']) OR $_POST['home_wickets'] < 0){
					echo "Home wickets is not valid.";
					exit();
				}
			}
			if($_POST['home_overs']){
				if(! $this->phpvalidator->is_numeric($_POST['home_overs']) OR $_POST['home_overs'] < 0){
					echo "Home overs is not valid.";
					exit();
				}
			}
		*/	
		/*	if(! $this->phpvalidator->is_natural($_POST['home_runs']) OR $_POST['home_runs'] < 0){
				echo "Home runs is not valid.";
				exit();
			}	*/
		/*	if($_POST['away_score']){
				if(! $this->phpvalidator->is_natural($_POST['away_score']) OR $_POST['away_score'] < 0){
					echo "Away score is not valid.";
					exit();
				}
			}
			if($_POST['away_wickets']){
				if(! $this->phpvalidator->is_natural($_POST['away_wickets']) OR $_POST['away_wickets'] < 0){
					echo "Away wickets is not valid.";
					exit();
				}
			}
			if($_POST['away_overs']){
				if(! $this->phpvalidator->is_numeric($_POST['away_overs']) OR $_POST['away_overs'] < 0){
					echo "Away overs is not valid.";
					exit();
				}
			}
		*/	
		/*	if(! $this->phpvalidator->is_natural($_POST['away_runs']) OR $_POST['away_runs'] < 0){
				echo "Away runs is not valid.";
				exit();
			}	*/
			
			$sport_id = intval($_POST['sport_id']);
			//if sport_id = 1: Test cricket: DRAW | other: NOT DRAW
			$MATCH = $this->match_entity->init('id', $_POST['id']);
			
			$MATCH->setHome($_POST['home']);
			$MATCH->setHomeScore(strlen($_POST['home_score']) ? $_POST['home_score']:'');
			$MATCH->setHomeWickets(strlen($_POST['home_wickets']) ? $_POST['home_wickets']:'');
			$MATCH->setHomeOvers(strlen($_POST['home_overs']) ? $_POST['home_overs']:'');
		//	$MATCH->setHomeRuns($_POST['home_runs']);
			$MATCH->setAway($_POST['away']);
			$MATCH->setAwayScore(strlen($_POST['away_score']) ? $_POST['away_score']:'');
			$MATCH->setAwayWickets(strlen($_POST['away_wickets']) ? $_POST['away_wickets']:'');
			$MATCH->setAwayOvers(strlen($_POST['away_overs']) ? $_POST['away_overs']:'');
		//	$MATCH->setAwayRuns($_POST['away_runs']);
			$MATCH->setResult($_POST['result']);
			$MATCH->setStartTime($startTime);
			$MATCH->setEndTime($endTime);
			$MATCH->setSportId($sport_id);
			$MATCH->setConvertionRate($convertionRate);
			$MATCH->setEnableConvertion($convertionEnable);
			$MATCH->setEmailNotifyEnable($this->input->post('email_notify_enable',NULL));
			$MATCH->setSmsNotifyEnable($this->input->post('sms_notify_enable',NULL));
			
			$MATCH->setFeedType($this->input->post('feed_type',NULL));
			$MATCH->setFeedKey($this->input->post('feed_key',NULL));
			$MATCH->setFeedMatchId($this->input->post('feed_match_id',NULL));
			$MATCH->setFeedCategoryId($this->input->post('feed_category_id',NULL));
			$MATCH->setTitle($this->input->post('title',NULL));
			
			$MATCH->update();
			
			$drawEntity = $this->event_entity->findDrawEventOfMatch($MATCH->getId());
			$rootEventCategoryEntity = $this->event_category_entity->getRootEventCategory($MATCH->getId());
			
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $rootEventCategoryEntity[0]->id);
			$EVENT_CATEGORY->setCategory("Who will win the match");
			$EVENT_CATEGORY->update();
			if($sport_id == 1){
				if(empty($drawEntity)){
					$event_id = $this->event_entity->createNewEventEntity();
					$EVENT = $this->event_entity->init('id', $event_id);
					$EVENT->setName("Draw");
					$EVENT->setTeamId(0);
					$EVENT->setMatchId($MATCH->getId());
					$EVENT->setStatus('living');
					$EVENT->setEventCategoryId($rootEventCategoryEntity[0]->id);
					$EVENT->setStartTime($startTime);
					$EVENT->setEndTime($endTime);
					$EVENT->setBetEnable('yes');
					$EVENT->setOdds(1);
					$EVENT->setIsRoot('yes');
					$EVENT->update();
					
					$EVENT_CATEGORY->setCategory("Match Result");
					$EVENT_CATEGORY->update();
				}
			}else{
				if(!empty($drawEntity)){
					$this->db->where('id',$drawEntity[0]->id)->delete(TBL_EVENT);
				}
			}
			if($this->input->post('use_default_event',TRUE) == 'yes'){ $this->add_default_event_to_match(0,$MATCH->getId(),$sport_id );}
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo "ok";
		exit();
	}
	
	function add_default_event_to_match($team_id, $match_id,$sport_id){
		$MATCH = $this->match_entity->init('id',$match_id);
		$HOME = clone_($this->team_entity->init('id',$MATCH->getHome()));
		$AWAY = clone_($this->team_entity->init('id',$MATCH->getAway()));
		
		$start_time = $MATCH->getStartTime();
		$end_time = $MATCH->getEndTime();
		
		$category_array = $this->pre_define_entity->getListCategoriesBySportId($sport_id);
		foreach($category_array as $cat){
			$event_category_id = $this->event_category_entity->createNewEventCategoryEntity($MATCH->getId());
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $event_category_id);
			$EVENT_CATEGORY->setCategory($cat->title);
			$EVENT_CATEGORY->setMatchId($match_id);
			$EVENT_CATEGORY->setStatus('living');
			$EVENT_CATEGORY->setIsRoot(NULL);
			$EVENT_CATEGORY->update();
			
			$event_array = $this->pre_define_entity->getListEventOfCategory($cat->id);
			foreach($event_array as $ev){
				$event_id = $this->event_entity->createNewEventEntity();
				$EVENT = $this->event_entity->init('id', $event_id);
				$event_name = str_replace( array('{###HOME###}', '{###AWAY###}'), array( $HOME->getName(), $AWAY->getName()), $ev->title);
				
				$EVENT->setName($event_name);
				$EVENT->setTeamId($team_id);
				$EVENT->setMatchId($match_id);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				//$EVENT->setStartTime($start_time);
				//$EVENT->setEndTime($end_time);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds($ev->odds);
				$EVENT->setIsRoot(NULL);
				$EVENT->update();
			}
		}
	}
	
	function update_ordering_category(){
		$match_id = $_POST['match_id'];
		$id_arr = array_filter( explode(',', $_POST['ids']) );
		$i=count($id_arr) +1;
		foreach($id_arr as $id){
			$this->db->where(array('match_id'=>$match_id, 'id'=>$id))->update(TBL_CATEGORY_EVENT, array('ordering'=>$i--));
		}
		echo 'ok';exit();
	}
	
	function event_category_open_hide(){
		$match_id = $_POST['match_id'];
		$category_id = $_POST['category_id'];
		$EVENT_CATEGORY = $this->event_category_entity->init('id', $category_id);
		$value = $EVENT_CATEGORY->getIsOpen() == 'yes' ? 'no' : 'yes';
		$EVENT_CATEGORY->setIsOpen($value);
		$EVENT_CATEGORY->update();
		echo 'ok';
	}
	
	function change_bet_status_match(){
		$MATCH = $this->match_entity->init('id', $_POST['id']);
		if($MATCH->getBetEnable() == 'yes'){
			$MATCH->setBetEnable('no');
		}else{
			$MATCH->setBetEnable('yes');
		}
		$MATCH->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo "ok";
		exit();
	}
	
	function event_category_submit(){
		if(!isset($_POST['id'])){
			$newId = $this->event_category_entity->createNewEventCategoryEntity($_POST['match_id']);
			
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $newId);
			$EVENT_CATEGORY->setCategory($_POST['category']);
			$EVENT_CATEGORY->setMatchId($_POST['match_id']);
			$EVENT_CATEGORY->setStatus('living');
			
			$EVENT_CATEGORY->update();
			$match_id = $_POST['match_id'];
		}else{
			$EVENT_CATEGORY = $this->event_category_entity->init('id', $_POST['id']);
			$EVENT_CATEGORY->setCategory($_POST['category']);
			$EVENT_CATEGORY->update();
			
			$match_id = $EVENT_CATEGORY->getMatchId();
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo $match_id;
		exit();
	}
	
	function event_submit(){
		$match_id = $_POST['match_id'];
		$MATCH = $this->match_entity->init('id', $match_id);
		$TOURNAMENT = $this->tournament_entity->init('id',$MATCH->getTournamentId());
		$dateTimeStart = sysDateTimeFormat($MATCH->getStartTime());
		$dateTimeEnd = sysDateTimeFormat($TOURNAMENT->getEndTime());
		
		if(!isset($_POST['id'])){
		/*	$startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			if( $startTime == 0 OR $endTime == 0 ){
				echo "Datetime not validated.";exit();
			}
			if( $startTime < $MATCH->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";exit();
			}
			if( $endTime > $TOURNAMENT->getEndTime() ){
				echo "End time not validated. (> {$dateTimeEnd})";exit();
			}
			*/
			if(! $this->phpvalidator->is_numeric($_POST['odds']) OR $_POST['odds'] <= 0){
				echo "Odds is not valid.";
				exit();
			}
			$newId = $this->event_entity->createNewEventEntity();
			$EVENT = $this->event_entity->init('id', $newId);
			$EVENT->setName($_POST['name']);
			$EVENT->setMatchId($match_id);
			$EVENT->setStatus('living');
			$EVENT->setEventCategoryId($_POST['event_category_id']);
			//$EVENT->setStartTime($startTime);
			//$EVENT->setEndTime($endTime);
			$EVENT->setBetEnable('yes');
			$EVENT->setOdds($_POST['odds']);
			$EVENT->update();
		}else{
			/* $startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			if( $startTime == 0 OR $endTime == 0 ){
				echo "Datetime not validated.";exit();
			}
			if( $startTime < $MATCH->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";exit();
			}
			if( $endTime > $TOURNAMENT->getEndTime() ){
				echo "End time not validated. (> {$dateTimeEnd})";exit();
			}
			*/
			if(! $this->phpvalidator->is_numeric($_POST['odds']) OR $_POST['odds'] <= 0){
				echo "Odds is not valid.";
				exit();
			}
			
			$EVENT = $this->event_entity->init('id', $_POST['id']);
			$EVENT->setName($_POST['name']);
			$EVENT->setEventCategoryId($_POST['event_category_id']);
			//$EVENT->setStartTime($startTime);
			//$EVENT->setEndTime($endTime);
			$EVENT->setOdds($_POST['odds']);
			$EVENT->update();
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo $match_id;
		exit();
	}
	
	function add_events_submit(){
		$match_id = $_POST['match_id'];
		$event_category_id = $_POST['category_id'];
		$MATCH = $this->match_entity->init('id', $match_id);
		$TOURNAMENT = $this->tournament_entity->init('id',$MATCH->getTournamentId());
		$dateTimeStart = sysDateTimeFormat($MATCH->getStartTime());
		$dateTimeEnd = sysDateTimeFormat($TOURNAMENT->getEndTime());
		 
		$numberEvents = count($_POST['name']); 
		$pass = true;
		for($i= 0; $i<$numberEvents ; $i++){
			/*$startTime =  convertToTimeStampFromFormat($_POST['start_time'][$i]);
			$endTime = convertToTimeStampFromFormat($_POST['end_time'][$i]);
			if( $startTime == 0 OR $endTime == 0 ){
				echo "Datetime not validated.";
				$pass = false;
				exit();
			}
			if( $startTime < $MATCH->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";
				$pass = false;
				exit();
			}
			if( $endTime > $TOURNAMENT->getEndTime() ){
				echo "End time not validated. (> {$dateTimeEnd})";
				$pass = false;
				exit();
			}
			*/
			if(! $this->phpvalidator->is_numeric($_POST['odds'][$i]) OR $_POST['odds'][$i] <= 0){
				echo "Odds is not valid.";
				$pass = false;
				exit();
			}
		}
		
		if($pass){
			for($i= 0; $i<$numberEvents ; $i++){
				//$startTime =  convertToTimeStampFromFormat($_POST['start_time'][$i]);
				//$endTime = convertToTimeStampFromFormat($_POST['end_time'][$i]);
				
				$newId = $this->event_entity->createNewEventEntity();
				$EVENT = $this->event_entity->init('id', $newId);
				$EVENT->setName($_POST['name'][$i]);
				$EVENT->setMatchId($match_id);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				//$EVENT->setStartTime($startTime);
				//$EVENT->setEndTime($endTime);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds($_POST['odds'][$i]);
				$EVENT->update();
			}
			$this->session->set_flashdata('success', lang('dataman.success'));
			echo $match_id;
			exit();
		}
	}
	
	function edit_events_submit(){
		$match_id = $_POST['match_id'];
		$event_category_id = $_POST['category_id'];
		$MATCH = $this->match_entity->init('id', $match_id);
		$TOURNAMENT = $this->tournament_entity->init('id',$MATCH->getTournamentId());
		$dateTimeStart = sysDateTimeFormat($MATCH->getStartTime());
		$dateTimeEnd = sysDateTimeFormat($TOURNAMENT->getEndTime());
		 
		$numberEvents = count($_POST['item_id']); 
		$pass = true;
		for($i= 0; $i<$numberEvents ; $i++){
			/* $startTime =  convertToTimeStampFromFormat($_POST['start_time'][$i]);
			$endTime = convertToTimeStampFromFormat($_POST['end_time'][$i]);
			if( $startTime == 0 OR $endTime == 0 ){
				echo "Datetime not validated.";
				$pass = false;
				exit();
			}
			if( $startTime < $MATCH->getStartTime() ){
				echo "Start time not validated. (< {$dateTimeStart})";
				$pass = false;
				exit();
			}
			if( $endTime > $TOURNAMENT->getEndTime() ){
				echo "End time not validated. (> {$dateTimeEnd})";
				$pass = false;
				exit();
			}
			*/
			if(! $this->phpvalidator->is_numeric($_POST['odds'][$i]) OR $_POST['odds'][$i] <= 0){
				echo "Odds is not valid.";
				$pass = false;
				exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['ordering'][$i]) OR $_POST['ordering'][$i] < 0){
				echo "Order number is not valid.";
				$pass = false;
				exit();
			}
			
		}
		
		if($pass){
			for($i= 0; $i<$numberEvents ; $i++){
				//$startTime =  convertToTimeStampFromFormat($_POST['start_time'][$i]);
				//$endTime = convertToTimeStampFromFormat($_POST['end_time'][$i]);
				
				$EVENT = $this->event_entity->init('id', $_POST['item_id'][$i]);
				$EVENT->setName($_POST['name'][$i]);
				$EVENT->setMatchId($match_id);
				$EVENT->setStatus('living');
				$EVENT->setEventCategoryId($event_category_id);
				//$EVENT->setStartTime($startTime);
				//$EVENT->setEndTime($endTime);
				$EVENT->setBetEnable('yes');
				$EVENT->setOdds($_POST['odds'][$i]);
				$EVENT->setOrdering(intval($_POST['ordering'][$i]));
				$EVENT->update();
			}
			$this->session->set_flashdata('success', lang('dataman.success'));
			echo $match_id;
			exit();
		}
	}
	
	function event_change_bet_status(){
		$EVENT = $this->event_entity->init('id', $_POST['id']);
		if($EVENT->getBetEnable() == 'yes'){
			$EVENT->setBetEnable('no');
		}else{
			$EVENT->setBetEnable('yes');
		}
		$EVENT->update();
		echo "ok";
		exit();
	}
	
	function set_event_result(){
		$EVENT = $this->event_entity->init('id', $_POST['id']);
		$EVENT->setResult($_POST['result']);
		$EVENT->update();
		echo $EVENT->getMatchId();
		exit;
	}
	
	function match_finish(){
		$MATCH = $this->match_entity->init('id',$_POST['id']);
		$TOURNAMENT = $this->tournament_entity->init('id', $_POST['tournament_id']);
		
	/**	if($MATCH->isMatchFinished()){
			echo "Missing. Match is finished.";
			exit();
		}
	
		if($MATCH->getStatus() != 'closed' ){
			echo "Missing. Match is not closed.";
			exit();
		}
	**/
	
		$canFinish = true;
		$eventArray = $this->event_entity->getLivingEventOfMatch($MATCH->getId());
		foreach($eventArray as $item){
			$EVENT = $this->event_entity->init('id',$item->id);
			if( $EVENT->getResult() == '' ){
				$canFinish = false;
				break;
			}
		}
		if( !$canFinish ){
			echo "Required set result of event firstly.";exit();
		}
	//////////////////////////////////MANUAL EVENTS////////////////////////////////////////	
		$canFinishManualEvent = true;
		$livingManualCategories = $this->category_manual_entity->getLivingCategoriesOfMatch($MATCH->getId());
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
			if($this->bet_manual_entity->isBettingStatusCategory($CAT_MANUAL->getKeyId())){
				$canFinishManualEvent = false;
				break;
			}
		}
		
		if(!$canFinishManualEvent){
			echo "Please set result of manual events before.";exit();
		}
		
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
			$bettingList = $this->bet_manual_entity->getBettingList($CAT_MANUAL->getKeyId());
			foreach($bettingList as $item){
				$BET_MANUAL = $this->bet_manual_entity->init('id',$item->id);
				$BET_MANUAL->setStatus('finished');
				$BET_MANUAL->processUserBetResult();
				$BET_MANUAL->update();
			}
			$CAT_MANUAL->setStatus('closed');
			$CAT_MANUAL->update();
		}
	//////////////////////////////////////////////////////////////////////////////////////////////////////
	
		$betArray = $this->bet_entity->getBetListOfMatch($MATCH->getId());
		foreach($betArray as $obj){
			$EVENT = $this->event_entity->init('id',$obj->event_id);
			$BET = $this->bet_entity->init('id', $obj->id);
			$BET->setStatus('finished');
			$BET->setResult($EVENT->getResult());
			$BET->update();
			$BET->processUserBetResult();
		}
		
		$eventArray = $this->event_entity->getLivingEventOfMatch($MATCH->getId());
		foreach($eventArray as $item){
			$EVENT = $this->event_entity->init('id',$item->id);
			$EVENT->setStatus('closed');
			$EVENT->update();
			$CAT = $this->event_category_entity->init('id',$EVENT->getEventCategoryId());
			$CAT->setStatus('closed');
			$CAT->update();
		}
		$MATCH->setStatus('closed');
		$MATCH->update();
		
		echo 'ok';
		exit();
	}
	
	function event_finish(){
		$EVENT = $this->event_entity->init('id',$_POST['event_id']);
		
	/*	if($EVENT->getStatus() != 'living'){
			echo "Not validated. Function can not work.";exit();
		}
	*/	 
		if( $EVENT->getResult() == '' ){
			echo "Required set result of event firstly.";exit();
		}
		
		$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
		foreach($listBet as $obj){
			$BET = $this->bet_entity->init('id', $obj->id);
			
			$BET->setStatus('finished');
			$BET->setResult($EVENT->getResult());
			$BET->update();
			
			$BET->processUserBetResult();
		}
		$EVENT->setStatus('closed');
		$EVENT->update();
		
		echo 'ok#'.$EVENT->getMatchId();
		exit();
	}
	
	function event_cancel(){
		$EVENT = $this->event_entity->init('id',$_POST['event_id']);
	/*	
		if( $EVENT->getStatus() != 'living' ){
			echo "Not validated. Function can not work.";exit();
		}
	*/	
		$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
		foreach($listBet as $obj){
			$BET = $this->bet_entity->init('id', $obj->id);
			
			$BET->setStatus('cancelled');
			$BET->setResult('cancelled');
			$BET->update();
			
			$BET->processUserBetResult();
		}
		$EVENT->setStatus('cancelled');
		$EVENT->update();
		
		echo 'ok#'.$EVENT->getMatchId();
		exit();
	}
	
	function event_category_finish(){
		$EVENT_CATEGORY = $this->event_category_entity->init('id', $_POST['event_category_id']);
		$listEventLiving = $this->event_entity->getLivingEventOfCategory($EVENT_CATEGORY->getId());
		$is_finish = true;
		
		foreach($listEventLiving as $item){
			$EVENT = $this->event_entity->init('id', $item->id);
			if( $EVENT->getResult() == '' ){
				$is_finish = false;
				break;
			}
		}
		
		if(!$is_finish){
			echo "Required set result of events firstly.";exit();
		}
		
		foreach($listEventLiving as $item){
			$EVENT = $this->event_entity->init('id', $item->id);
			$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
			foreach($listBet as $obj){
				$BET = $this->bet_entity->init('id', $obj->id);
				
				$BET->setStatus('finished');
				$BET->setResult($EVENT->getResult());
				$BET->update();
				
				$BET->processUserBetResult();
			}
			$EVENT->setStatus('closed');
			$EVENT->update();
		}
		$EVENT_CATEGORY->setStatus('closed');
		$EVENT_CATEGORY->update();		
		
		echo 'ok#'.$EVENT_CATEGORY->getMatchId();
		
	}
	
	function event_category_cancel(){
		$EVENT_CATEGORY = $this->event_category_entity->init('id', $_POST['event_category_id']);
		
		if( $EVENT_CATEGORY->getStatus() != 'living' ){
			echo "Not validated. Function can not work.";exit();
		}
		
		$listEventLiving = $this->event_entity->getLivingEventOfCategory($EVENT_CATEGORY->getId());
		foreach($listEventLiving as $item){
			$EVENT = $this->event_entity->init('id', $item->id);
			
			$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
			foreach($listBet as $obj){
				$BET = $this->bet_entity->init('id', $obj->id);
				
				$BET->setStatus('cancelled');
				$BET->setResult('cancelled');
				$BET->update();
				
				$BET->processUserBetResult();
			}
			$EVENT->setStatus('cancelled');
			$EVENT->update();
		}
		$EVENT_CATEGORY->setStatus('cancelled');
		$EVENT_CATEGORY->update();
		
		
		echo 'ok#'.$EVENT_CATEGORY->getMatchId();
		exit();
	}
	
	function match_cancel(){
		$MATCH = $this->match_entity->init('id', $_POST['match_id']);
	/*	
		if( $MATCH->getStatus() != 'living' ){
			echo "Not validated. Function can not work.";exit();
		}
	*/	
		$listEventLiving = $this->event_entity->getLivingEventOfMatch($MATCH->getId());
		foreach($listEventLiving as $item){
			$EVENT = $this->event_entity->init('id', $item->id);
			$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
			foreach($listBet as $obj){
				$BET = $this->bet_entity->init('id', $obj->id);
				$BET->setStatus('cancelled');
				$BET->setResult('cancelled');
				$BET->update();
				$BET->processUserBetResult();
			}
			$EVENT->setStatus('cancelled');
			$EVENT->update();
			$CAT = $this->event_category_entity->init('id',$EVENT->getEventCategoryId());
			$CAT->setStatus('cancelled');
			$CAT->update();
		}
		
		$livingManualCategories = $this->category_manual_entity->getLivingCategoriesOfMatch($MATCH->getId());
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
			$bettingList = $this->bet_manual_entity->getBettingList($CAT_MANUAL->getKeyId());
			foreach($bettingList as $item){
				$BET_MANUAL = $this->bet_manual_entity->init('id',$item->id);
				$BET_MANUAL->setStatus('cancelled');
				$BET_MANUAL->setResult('cancelled');
				$BET_MANUAL->processUserBetResult();
				$BET_MANUAL->update();
			}
			$CAT_MANUAL->setStatus('cancelled');
			$CAT_MANUAL->update();
		}
		
		$MATCH->setStatus('cancelled');
		$MATCH->update();
		
		echo 'ok';
		exit();
	}
	
	function match_show_feature(){
		$MATCH = $this->match_entity->init('id', $_POST['match_id']);
		if($MATCH->getShowFeature() != 1){
			$MATCH->setShowFeature(1);
		}else{
			$MATCH->setShowFeature(0);
		}
		$MATCH->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function batsman_submit(){
		$data = $_POST['data'];
		$MATCH = $this->match_entity->init('id', $data['match_id']);
		
		$tmp  = array();
		$tmp[] = array('batsman' => $data['name_home1'] , 'r' => $data['r_home1'] , 'b' => $data['b_home1']);
		$tmp[] = array('batsman' => $data['name_home2'] , 'r' => $data['r_home2'] , 'b' => $data['b_home2']);
		
		$batmanArray = $tmp;
		$MATCH->setBatmanInfo(serialize($batmanArray));
		$MATCH->update();
		
		echo "Save done.";
		exit();
	}
	
	function scorecard_add_submit(){
		$data = $_POST['data'];
	
		if(!isset($data['id'])){
			$MATCH = $this->match_entity->init('id', $data['match_id']);
			$this->db->set('value', $data['value']);
			$this->db->set('type', $MATCH->getFeedType());
			$this->db->set('key', $MATCH->getFeedKey());
			$this->db->set('match_id', $MATCH->getFeedMatchId());
			$this->db->set('over_index', intval( $data['index'] ) );
			$this->db->set('category_id', $MATCH->getFeedCategoryId());
			$this->db->insert(TBL_SCORECARD);
		}else{
			$this->db->set('value', $data['value']);
			$this->db->set('over_index', intval( $data['index'] ) );
			$this->db->where( array('id'=>$data['id']) )->update(TBL_SCORECARD);
		}
		
		exit();
	}
	
	function score_item_delete(){
		$this->db->where( array('id'=>$_POST['id']) )->delete(TBL_SCORECARD);
		exit();
	}
	
	function remove_xml_match_update(){
		$MATCH = $this->match_entity->init('id',$_POST['match_id']);
		$MATCH->setFeedType(NULL);
		$MATCH->setFeedKey(NULL);
		$MATCH->setFeedMatchId(NULL);
		$MATCH->setFeedCategoryId(NULL);
		$MATCH->setBatmanInfo(NULL);
		$MATCH->setEndTime(time());
		$MATCH->setStatus('cancelled');
		$MATCH->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit(); 
	}
	
// end class	
}
